package com.lynx.service.impl;

import java.util.LinkedList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lynx.mapper.cb.JobInfoMapper;
import com.lynx.mapper.cb.model.JobInfoPO;
import com.lynx.service.JobCenterService;
import com.lynx.service.model.JobInfoBO;

import javax.annotation.PostConstruct;

/**
 * @author chris.liu
 * @version 5/6/14 4:07 PM
 */
@Service("jobCenterService")
public class JobCenterServiceImpl implements JobCenterService {

	private static final int PAGE_SIZE = 2;
	private static int jobNum = 0;

	@Autowired
	private JobInfoMapper jobInfoMapper;

	@PostConstruct
	private void init() {
		try {
			jobNum = jobInfoMapper.getJobNum();
		} catch (Exception e) {

		}
	}

	@Override
	public int getJobInfoPageSize() {
		if (jobNum % PAGE_SIZE > 0) {
			return jobNum / PAGE_SIZE + 1;
		} else {
			return jobNum / PAGE_SIZE;
		}
	}

	@Override
	public JobInfoBO getJobInfo(int id) {
		JobInfoPO po = jobInfoMapper.getJobInfo(id);
		return po2bo(po);
	}

	@Override
	public List<JobInfoBO> getJobInfos(int page) {
		int offset = (page - 1) > 0 ? (page - 1) * PAGE_SIZE : 0;
		List<JobInfoPO> pos = jobInfoMapper.getJobInfos(offset, PAGE_SIZE);

		List<JobInfoBO> bos = new LinkedList<JobInfoBO>();
		if (pos == null || pos.size() <= 0) {
			return bos;
		}

		for (JobInfoPO po : pos) {
			bos.add(po2bo(po));
		}
		return bos;
	}

	@Override
	public boolean addJob(JobInfoBO job) {
		JobInfoPO po = bo2po(job);
		try {
			jobInfoMapper.addJobInfo(po);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	@Override
	public JobInfoBO updateJobInfo(JobInfoBO job) {
		jobInfoMapper.updateJobInfo(bo2po(job));
		JobInfoPO po = jobInfoMapper.getJobInfo(job.getId());
		return po2bo(po);
	}

	@Override
	public boolean deleteJob(int id) {
		JobInfoPO po = jobInfoMapper.getJobInfo(id);
		if (po != null) {
			jobInfoMapper.deleteJobInfo(id);
			return true;
		} else {
			return false;
		}
	}

	private JobInfoBO po2bo(JobInfoPO po) {
		if (po == null) {
			return null;
		}

		JobInfoBO bo = new JobInfoBO();
		bo.setId(po.getId());
		bo.setName(po.getName());
		bo.setClazz(po.getClazz());
		bo.setCron(po.getCron());
		bo.setDesc(po.getDesc());
		bo.setStatus(po.getStatus());
        bo.setLstLog(po.getLstLog());
		return bo;

	}

	private JobInfoPO bo2po(JobInfoBO bo) {
		if (bo == null) {
			return null;
		}
		JobInfoPO po = new JobInfoPO();
		po.setId(bo.getId());
		po.setName(bo.getName());
		po.setClazz(bo.getClazz());
		po.setCron(bo.getCron());
		po.setDesc(bo.getDesc());
		po.setStatus(bo.getStatus());
        po.setLstLog(bo.getLstLog());
		return po;
	}
}
